package org.ns.summer.beans.beanprocessor;

import org.ns.summer.aop.AopUtils;
import org.ns.summer.beans.ConfigurableBeanFactory;
import org.ns.summer.beans.InitializingBeanPostProcessor;
import org.ns.summer.beans.anns.Autowired;
import org.ns.summer.beans.anns.Qualifier;
import org.ns.summer.beans.error.BeansException;
import org.ns.summer.core.AnnotationUtils;
import org.ns.summer.core.FieldUtils;

import java.lang.reflect.Field;
import java.util.List;

public class AutowritedBeanProcessor implements InitializingBeanPostProcessor {

    @Override
    public void preHandler(ConfigurableBeanFactory beanFactory, Object bean, String beanName) throws BeansException {
        Class<?> targetType = AopUtils.getTargetType(bean.getClass());
        List<Field> fields = FieldUtils.findFieldsAll(targetType, Autowired.class);
        try {
            for (Field field : fields) {
                String name = field.getName();
                if (AnnotationUtils.existAnnotation(field, Qualifier.class)) {
                    Qualifier qualifier = (Qualifier) AnnotationUtils.getAnnotation(field, Qualifier.class);
                    String value = qualifier.value().trim();
                    if (!value.isEmpty()) {
                        name = value;
                    }
                }
                if (!field.isAccessible()) {
                    field.setAccessible(true);
                }
                Object object = beanFactory.getBean(name);
                field.set(bean, object);

            }
        } catch (BeansException be) {
            throw be;
        } catch (Exception e){
            throw new BeansException("beanName:" + beanName, e);
        }

    }
}
